package com.health.coupon.security;

import com.health.coupon.constant.Constants;
import com.health.coupon.utils.JwtTokenUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * <h1>权限拦截器</h1>
 * Created by fangjicai on 2020/3/13.
 */
@Component
public class AuthCheckInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest,
                             HttpServletResponse httpServletResponse, Object o) throws Exception {

        //约定商户校验信息放到http请求头中
        String token = httpServletRequest.getHeader(Constants.TOKEN_STRING);

        if (StringUtils.isEmpty(token)) {
            throw new Exception("Header 中缺少 " + Constants.TOKEN_STRING + "!");
        }

//        if (!token.equals(Constants.TOKEN)) {
//            throw new Exception("Header 中 " + Constants.TOKEN_STRING + "错误!");
//        }
        //解析token
        boolean b = JwtTokenUtils.parseToken(token);
        //token认证通过后，存储到本地线程局部变量表中
        if(b){
            //如果token存在则存放在threadlocal中
            AccessContext.setToken(token);
        }
        return b;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest,
                           HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    //在处理完请求后，释放threadlocal资源
    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest,
                                HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
        AccessContext.clearAccessKey();
    }

}
